import {
  Injectable,
  NestInterceptor,
  ExecutionContext,
  CallHandler,
} from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ResponseSuccess } from '../response/response.interface';

@Injectable()
export class TransformInterceptor<T>
  implements NestInterceptor<T, ResponseSuccess<T>>
{
  intercept(
    context: ExecutionContext,
    next: CallHandler,
  ): Observable<ResponseSuccess<T>> {
    return next.handle().pipe(
      map(data => {
        // 如果返回的已经是 ResponseSuccess 或 ResponseError 类型，直接返回
        if (
          data &&
          (data instanceof ResponseSuccess || 
           (typeof data === 'object' && 'code' in data))
        ) {
          return data;
        }
        // 否则包装成 ResponseSuccess
        return new ResponseSuccess(data);
      }),
    );
  }
} 